/**
 * Created by zhangsl
 */
import Basic from "../Basic";
import axios from "axios";
import * as  errorCode from "../error-code";

export default class Network extends Basic {
  public SERVICE_URL: string =
           process.env.NODE_ENV === "production" ?
            "https://mhdz.mooddo.com" :
            "https://vpdami.mooddo.com";
  private instance: any      = null;

  constructor() {
    super();
    this.instance = axios.create({
      baseURL: this.SERVICE_URL,
      timeout: 1000 * 60 * 5,
    });
    this.setHeader();
    this.instance.interceptors.response.use(this.filterResponse);
  }

  public filterResponse(res: any) {
    console.log("请求结束");
    if ( !res.data.IsSuccess ) {
      let errorInfo = "";
      if ( res.data.Code < 0 ) {
        errorInfo = (errorCode as any)[`codea${res.data.Code * -1}`];
      } else {
        errorInfo = (errorCode as any)[`code${res.data.Code}`];
      }

      if ( 1006 !== res.data.Code && 401 !== res.data.Code) {
        // 登陆失效不提示
        alert("test err");
      }
      throw new Error(`ajax error: ${res.data.Message} ${errorInfo}`);
    }
    if ( res.data.Ext ) {
      res.data = {data: res.data.Data, ext: res.data.Ext};
    }
    return res.data.Data;
  }

  public  ajax_post(url: string, sendData: any = {}) {
    this.setHeader();
    return this.instance.post(url, sendData).catch((e: any) => console.log("post success"));
  }

  public ajax_get(url: string, sendData: any = {}) {
    this.setHeader();
    return this.instance.get(url, {params: sendData}).catch((e: any) => console.log("get success"));
  }

  public setHeader() {
    this.instance.defaults.headers.common.Authorization = `Bearer ${localStorage.getItem("token") || ""}`;
  }
  public post(url: string) {
    return ( sendData: any ) => {
      return this.ajax_post(url, sendData);
    };
  }

  public get(url: string) {
    return ( sendData: any ) => {
      return this.ajax_get(url, sendData);
    };
  }
}
